﻿using System;
using System.Windows;
using System.ComponentModel;
using nRoute.Components.TypeConverters;
using System.Windows.Data;
using System.Windows.Interactivity;

namespace nRoute.Samples.OfficerXcel.Behaviors
{
    public class SetDataContextPropertyAction 
        : TriggerAction<FrameworkElement>
    {
        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(object), typeof(SetDataContextPropertyAction),
            new PropertyMetadata(null));

        string _propertyName;

#region Properties

        public string PropertyName
        {
            get { return _propertyName; }
            set { _propertyName = value; }
        }

        [TypeConverter(typeof(ConvertFromStringConverter))]
        public Object Value
        {
            get { return GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

#endregion

#region Trigger Related

        protected override void Invoke(object parameter)
        {
            // basic check
            if (string.IsNullOrEmpty(this.PropertyName)) return;
            if (AssociatedObject.DataContext == null) return;

            // we set the value
            var _dataContext = this.AssociatedObject.DataContext;
            var _propertyInfo = _dataContext.GetType().GetProperty(this.PropertyName);
            if (_propertyInfo == null || !_propertyInfo.CanWrite) return;

            // we convert and set the value
            var _value = Value != null ? ConverterHelper.ConvertToType(Value, _propertyInfo.PropertyType) : null;
            _propertyInfo.SetValue(_dataContext, _value, null);
        }

#endregion

    }
}
